<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="auto">
            <el-row>
                <el-form-item label="Date" label-width="auto">
                    <el-col :span="4">
                        <el-date-picker
                            v-model="daterangeDate"
                            style="width:220px"
                            value-format="yyyy-MM-dd"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="-"
                            start-placeholder="Start Date"
                            end-placeholder="End Date"
                            :picker-options="pickerOptions"
                        ></el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="EmployeeID" prop="employeeId" label-width="auto"
                              v-has-permi="['business:goodCatch:searchAll']">
                    <el-col :span="4">
                        <el-input style="width:150px"
                                  v-model="queryParams.employeeId"
                                  placeholder="Input EmployeeID"
                                  clearable
                                  @keyup.enter.native="handleQuery"
                        />
                    </el-col>
                </el-form-item>
                <el-form-item label="Name" prop="employeeName" label-width="auto"
                              v-has-permi="['business:goodCatch:searchAll']">
                    <el-col :span="4">
                        <el-input style="width:100px"
                                  v-model="queryParams.employeeName"
                                  placeholder="Input"
                                  clearable
                                  @keyup.enter.native="handleQuery"
                        />
                    </el-col>
                </el-form-item>
                <el-form-item label="Dept." prop="deptId" label-width="auto"
                              v-has-permi="['business:goodCatch:searchAll']">
                    <el-col :span="4">
                        <el-select v-model="queryParams.deptId" style="width:100px" placeholder="Dept."
                                   clearable>
                            <el-option
                                v-for="item in deptList "
                                :key="item.deptId"
                                :label="item.deptName"
                                :value="item.deptId"
                            />
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="Owner" prop="owner" label-width="auto"
                              v-has-permi="['business:goodCatch:searchAll']">
                    <el-col :span="4">
                        <el-input style="width:100px"
                                  v-model="queryParams.owner"
                                  placeholder="Input"
                                  clearable
                                  @keyup.enter.native="handleQuery"
                        />
                    </el-col>
                </el-form-item>
                <el-form-item label="OwnerDept." prop="ownerDept" label-width="auto"
                              v-has-permi="['business:goodCatch:searchAll']">
                    <el-col :span="4">
                        <el-select v-model="queryParams.ownerDept" style="width:100px" placeholder="OwnerDept."
                                   clearable>
                            <el-option
                                v-for="item in deptList "
                                :key="item.ownerDept"
                                :label="item.deptName"
                                :value="item.deptId"
                            />
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="Status" prop="status">
                    <el-col :span="4">
                        <el-select v-model="queryParams.status" style="width:100px" placeholder="Status"
                                   clearable>
                            <el-option
                                v-for="dict in dict.type.business_status"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                            />
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="Reconfirm" prop="reconfirm">
                    <el-col :span="4">
                        <el-select v-model="queryParams.reconfirm" style="width:110px" placeholder="reconfirm"
                                   clearable>
                            <el-option
                                v-for="dict in dict.type.business_goodcatch_reconfirm"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                            />
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label-width="auto">
                    <el-col :span="4">
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">Search
                        </el-button>
                    </el-col>
                </el-form-item>
                <el-form-item label-width="auto">
                    <el-col :span="4">
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>
                    </el-col>
                </el-form-item>
            </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:goodCatch:add']"
                >Add
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['business:goodCatch:remove']"
                >Delete
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['business:goodCatch:export']"
                >Export
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="info"
                    plain
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-hasPermi="['business:goodCatch:import']"
                >import
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-close"
                    size="mini"
                    :disabled="reClosedMultiple"
                    @click="handleReClosed"
                    v-hasPermi="['business:goodCatch:reconfirm']"
                >ReClosed
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading"
                  ref="goodCatchTable"
                  :data="goodCatchList"
                  @selection-change="handleSelectionChange">
            <!--                  :height="tableMaxHeight"-->
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column
                label="No."
                type="index"
                width="50"/>
            <el-table-column label="No." width="*" align="center" prop="id" v-if="false"/>
            <el-table-column label="Date" align="center" prop="date" width="100">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="Dept." width="60" align="center" prop="deptId" :formatter="deptFormatter"/>
            <el-table-column label="EmployeeID" width="100" align="center" prop="employeeId"/>
            <el-table-column label="Name" width="100" align="center" prop="employeeName"/>
            <el-table-column label="Title" width="120" align="left" prop="title"/>
            <el-table-column label="Description" width="250" align="left" prop="description" :show-overflow-tooltip="false"/>
            <el-table-column label="Owner" width="*" align="center" prop="owner"/>
            <el-table-column label="Solution" width="200" align="left" prop="solution" :show-overflow-tooltip="false"/>
            <!--            <el-table-column label="Feasibility" align="center" prop="feasibility">
                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.business_goodcatch_feasibility" :value="scope.row.feasibility"/>
                            </template>
                        </el-table-column>-->
            <el-table-column label="DueDate" align="center" prop="dueDate" width="100">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="ClosingDate" align="center" prop="closingDate" width="100">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.closingDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="Status" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.business_status" :value="scope.row.status"/>
                </template>
            </el-table-column>


            <el-table-column label="Reconfirm" width="90" align="center" prop="reconfirm">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.business_goodcatch_reconfirm" :value="scope.row.reconfirm"/>
                </template>
            </el-table-column>
            <!--            <el-table-column label="Comment" width="200" align="left" prop="comment" :show-overflow-tooltip="false"/>
                        <el-table-column label="Reason" width="200" align="left" prop="reason" :show-overflow-tooltip="false"/>-->
            <el-table-column label="Attachment" width="100" align="center" prop="attachment">
                <template v-slot="scope">
                    <el-popover
                        placement="right"
                        width="400"
                        trigger="click">
                        <span v-if="showFileList(scope.row).len > 0">
                        <el-link target="_blank"
                                 v-for="fileUrl in showFileList(scope.row).data" type="primary" :key="fileUrl"
                                 :href="fileUrl">{{ fileUrl.slice(fileUrl.lastIndexOf("/") + 1) }}
                        </el-link>
                            </span>
                        <span v-else>No File</span>
                        <el-link slot="reference" type="primary">File Query</el-link>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="Remark" align="center" prop="remark" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    {{parseArrayToStr(scope.row.remark)}}
                </template>
            </el-table-column>
            <el-table-column label="Operate" align="center" class-name="small-padding fixed-width" width="100" fixed="right">
                <template slot-scope="scope">
                    <el-button
                        type="warning"
                        size="small"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['business:goodCatch:edit']"
                    >Edit
                    </el-button>
                    <!--                    <el-button-->
                    <!--                        size="mini"-->
                    <!--                        type="text"-->
                    <!--                        icon="el-icon-delete"-->
                    <!--                        @click="handleDelete(scope.row)"-->
                    <!--                        v-hasPermi="['business:goodCatch:remove']"-->
                    <!--                    >Delete-->
                    <!--                    </el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改goodCatch对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="50%" :append-to-body="true" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="auto">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="EmployeeID" prop="employeeId">
                            <el-input type="" v-model="form.employeeId" placeholder="Input EmployeeID" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="Name" prop="employeeName">
                            <el-input v-model="form.employeeName" placeholder="Input Name" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="Dept." prop="DeptId">
                            <el-select v-model="form.deptId" placeholder="Dept." disabled>
                                <el-option
                                    v-for="item in deptList"
                                    :key="item.deptId"
                                    :label="item.deptName"
                                    :value="parseInt(item.deptId)">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="Date" prop="date">
                            <el-date-picker clearable
                                            readonly
                                            style="width: 100%"
                                            v-model="form.date"
                                            type="date"
                                            value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="Title" prop="title">
                    <el-input v-model="form.title" placeholder="Input Title" :disabled="editPermit"/>
                </el-form-item>
                <el-form-item label="Description" prop="description">
                    <el-input v-model="form.description" :rows="4" type="textarea" placeholder="Input"  :disabled="editPermit"/>
                </el-form-item>
                <el-divider></el-divider>
                <!--                <el-form-item label="Feasibility" prop="feasibility">
                                    <el-select v-model="form.feasibility" placeholder="Feasibility"  :disabled="editPermit">
                                        <el-option
                                            v-for="dict in dict.type.business_goodcatch_feasibility"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>-->
                <el-row>
                    <el-col :span="15">
                        <el-form-item label="Owner" prop="owner">
                            <el-autocomplete
                                :disabled="editPermit"
                                class="inline-input"
                                v-model="form.owner"
                                :fetch-suggestions="querySearch"

                                placeholder="Input Name"
                                :trigger-on-focus="false"
                                @select="handleSelect"
                            ></el-autocomplete>

                            <!--                    <el-select
                                                    v-model="form.owner"
                                                    filterable
                                                    remote
                                                    reserve-keyword
                                                    allow-create
                                                    placeholder="Owner"
                                                    :remote-method="querySearch"
                                                    @change="selectOwnerChange"
                                                    :loading="loading">
                                                    <el-option
                                                        v-for="(item,index) in filterUserList"
                                                        :key="index"
                                                        :label="item.value"
                                                        :value="index">
                                                    </el-option>
                                                </el-select>-->

                            <el-popover
                                placement="right"
                                title="OwnerHistroy"
                                trigger="click"
                            >
                                <el-table :data="parseJson(form.ownerHistory)">
                                    <el-table-column width="200" property="owner.userName" label="Owner"></el-table-column>
                                    <el-table-column width="200" property="date" label="Date">
                                        <template slot-scope="scope">
                                            <span>{{ parseTime(scope.row.date) }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column width="200" property="editor" label="Editor"></el-table-column>
                                </el-table>
                                <el-button slot="reference" style="margin-left: 5px;" >OwnerHistory</el-button>
                            </el-popover>

                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="DueDate" prop="dueDate">
                            <el-date-picker clearable
                                            :readonly="editPermit"
                                            v-model="form.dueDate"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            placeholder="DueDate">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="Solution" prop="solution">
                    <el-input v-model="form.solution" :rows="4" type="textarea" placeholder="Input"  :disabled="editPermit" :maxlength="1000"/>
                </el-form-item>
                <el-divider></el-divider>
                <el-row>
                    <!--                    <el-col :span="12">
                                            <el-form-item label="DueDate" prop="dueDate">
                                                <el-date-picker clearable
                                                                :readonly="editPermit"
                                                                v-model="form.dueDate"
                                                                type="date"
                                                                value-format="yyyy-MM-dd"
                                                                placeholder="DueDate">
                                                </el-date-picker>
                                            </el-form-item>
                                        </el-col>-->
                    <el-col :span="12">
                        <el-form-item label="Status" prop="status">
                            <el-select v-model="form.status" @change="selectStatusChange" placeholder="Status"  :disabled="editPermit" >
                                <el-option
                                    v-for="dict in dict.type.business_status"
                                    :key="dict.value"
                                    :label="dict.label"
                                    :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="ClosingDate" prop="closingDate" v-if="form.status==3">
                            <el-date-picker clearable
                                            :readonly="editPermit"
                                            v-model="form.closingDate"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            placeholder="ClosingDate">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-form-item v-if="form.status==4" label="Reason" prop="reason">
                    <el-input v-model="form.reason" :rows="4" type="textarea" placeholder="Input"  :disabled="editPermit"/>
                </el-form-item>
                <el-divider></el-divider>
                <!--                <el-row>-->
                <!--                    <el-col :span="12">
                                        <el-form-item label="Status" prop="status">
                                            <el-select v-model="form.status" placeholder="Status"  :disabled="editPermit">
                                                <el-option
                                                    v-for="dict in dict.type.business_status"
                                                    :key="dict.value"
                                                    :label="dict.label"
                                                    :value="dict.value"
                                                ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>-->
                <!--                    <el-col :span="12">-->
                <el-form-item label="Reconfirm" prop="reconfirm" >
                    <el-select v-model="form.reconfirm"
                               @change="reconfirmChange" placeholder="Reconfirm"  :disabled="showReconfirm">
                        <el-option
                            v-for="dict in dict.type.business_goodcatch_reconfirm"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <!--                    </el-col>-->
                <!--                </el-row>-->
                <el-form-item v-if="showComment" label="Comment" prop="comment">
                    <el-input v-model="form.comment" :rows="4" type="textarea" placeholder="Input"  :disabled="editPermit"/>
                </el-form-item>
                <el-divider></el-divider>

                <el-form-item label="RemarK" prop="remarkNew">
                    <div v-for="(item,index) in parseJson(form.remark)">{{item}}<el-divider style="margin: 0"/></div>
                    <el-input v-model="form.remarkNew" :rows="4" type="textarea" placeholder="Remark"  :disabled="editPermit" :maxlength="1000"/>
                </el-form-item>


                <el-form-item label="Attachment" prop="attachment">
                    <FileUpload  :disable="editPermit" v-model="form.attachment"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">Submit</el-button>
                <el-button @click="cancel">Cancel</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport"/>
                        是否更新已经存在的用户数据
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                             @click="importTemplate">下载模板
                    </el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listGoodCatch,
    getGoodCatch,
    delGoodCatch,
    addGoodCatch,
    updateGoodCatch,
    getDeptList,
    getUserNameList, reClosedGoodCatch
} from "@/api/business/goodCatch";
import {getToken} from "@/utils/auth";
import dateUtils from "@/components/DateUtils.vue";

export default {
    name: "GoodCatch",
    dicts: ['business_status', 'business_goodcatch_feasibility','business_goodcatch_reconfirm'],
    data() {
        return {
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            showComment:false,
            showReason:false,
            user: {},
            deptList: [],
            // 遮罩层
            loading: true,
            selectOwnerItem:null,
            userNameList: [],
            userDeptOwner:'',
            filterUserList:[],
            // 显示reconfirm
            showReconfirm: true,
            editPermit: false,
            reClosedMultiple:true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // goodCatch表格数据
            goodCatchList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // Attachment时间范围
            daterangeDate: new Date(),
            business_status:[],
            originBusinessStatus:[],
            isOwnerStatus:3,
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: {Authorization: "Bearer " + getToken()},
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/business/goodCatch/importData"
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                date: null,
                deptId: null,
                employeeId: null,
                employeeName: null,
                ownerId: null,
                owner: null,
                ownerDept:null,
                solution:null,
                title: null,
                status: null,
                reconfirm:null,
                comment:null,
                reason:null,
                attachment: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                title: [
                    {required: true, message: "Title Not Null", trigger: "blur"}
                ],
                description: [
                    {required: true, message: "Description Not Null", trigger: "blur"}
                ],
                feasibility: [
                    {required: true, message: "Feasibility Not Null", trigger: "blur"}
                ],
                ownerId: [
                    {required: false, message: "Owner Not Null", trigger: "blur"}
                ],
                solution: [
                    {required: false, message: "Solution Not Null", trigger: "blur"}
                ],
                dueDate: [
                    {required: false, message: "DueDate Not Null", trigger: "blur"}
                ],
                closingDate: [
                    {required: false, message: "ClosingDate Not Null", trigger: "blur"}
                ],
                status: [
                    {required: true, message: "Status Not Null", trigger: "change"}
                ],
                remark: [
                    {required: false, message: "RemarK Not Null", trigger: "blur"}
                ],
                comment: [
                    {required: false, message: "Comment Not Null", trigger: "blur"}
                ],
                reason: [
                    {required: false, message: "Reason Not Null", trigger: "blur"}
                ],
            }
        };
    },
    created() {
        this.user = this.$store.state.user;
        this.originBusinessStatus =  [
            {
                "dictCode": 100,
                "dictSort": 0,
                "dictLabel": "Open",
                "dictValue": "1",
                "dictType": "business_status",
                "cssClass": null,
                "listClass": "primary",
                "isDefault": "N",
                "status": "0",
                "default": false
            },
            {
                "dictCode": 101,
                "dictSort": 2,
                "dictLabel": "Ongoing",
                "dictValue": "2",
                "dictType": "business_status",
                "cssClass": "",
                "listClass": "warning",
                "isDefault": "N",
                "status": "0",
                "default": false
            },
            {
                "dictCode": 102,
                "dictSort": 3,
                "dictLabel": "Closed",
                "dictValue": "3",
                "dictType": "business_status",
                "cssClass": null,
                "listClass": "success",
                "isDefault": "N",
                "status": "0",
                "default": false
            }
        ]
        this.getDeptList();
        this.getList();
        this.getUserNameList();
    },
    /*computed: {
        tableMaxHeight(){
            return window.innerHeight - 315 + 'px';
        }
    },*/
    methods: {
        querySearch(queryString, cb) {
            let names = this.userNameList;
            let results = queryString ? names.filter(name => name.value.startsWith(queryString)) : names;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        /*querySearch(queryString, cb) {
            console.log(queryString)
            let names = this.userNameList;

            this.filterUserList=this.userNameList.filter(item=>item.value.toLowerCase().startsWith(queryString))


            //let results = queryString ? names.filter(name => name.value.userName.startsWith(queryString)) : names;
            // 调用 callback 返回建议列表的数据
            console.log(this.filterUserList)
            //cb(results);
        },*/
        parseArrayToStr(array){
            if (undefined === array || "" === array) {
                return ''
            }else{
                console.log(array)
                var list=this.parseJson(array);
                if(list!=null){
                    return list.join(";")
                }
                return  "";
            }
        },
        parseJson(str){
            if (undefined === str || "" === str){
                return []
            }else{
                try {
                    return JSON.parse(str)
                }catch (e){
                    return [str]
                }
            }
        },
        reconfirmChange(e) {
            if (e === 'closed') {
                // 选择close自动增加时间
                /*this.form.closingDate = new Date()*/
                this.showComment = false;
                this.rules.comment[0].required = false;
            } else if (e === 'reject') {
                // 选择reject必须校验
                this.showComment = true;
                this.rules.comment[0].required = true;
            } else {
                this.rules.comment[0].required = false;
                this.showComment = false;
                /*this.form.closingDate = null*/
            }
        },
        /*statusChange(t) {
            if (t === 'closed') {
                // 选择close自动增加时间
                /!*this.form.closingDate = new Date()*!/
                this.showReason = false;
                this.rules.reason[0].required = false;
            } else if (t === 'reject') {
                // 选择reject必须校验
                this.showReason = true;
                this.rules.reason[0].required = true;
            } else {
                this.rules.reason[0].required = false;
                this.showReason = false;
                /!*this.form.closingDate = null*!/
            }
        },*/


        /*querySearch(queryString) {
            console.log(queryString)
            this.filterUserList = this.userNameList.filter(item => {
                return item.userName.toLowerCase().startsWith(queryString);
            })
        },*/
        selectStatusChange(item){
            /*if (item === '3') {
                // 选择close自动增加时间
                this.form.closingDate = new Date()
                this.showReason = false;
                this.rules.reason[0].required = false;
            } else if (item === '4') {
                // 选择reject必须校验
                this.showReason = true;
                this.rules.reason[0].required = true;
            } else {
                this.rules.reason[0].required = false;
                this.showReason = false;
                this.form.closingDate = null
            }*/
            if (item){
                if (this.isOwnerStatus === 0){
                    this.business_status = this.originBusinessStatus.filter(i=>i.dictLabel === 'Ongoing')
                }else if(this.isOwnerStatus === 1){
                    this.business_status = this.originBusinessStatus.filter(i=>i.dictLabel !== 'Ongoing')
                }else{
                    this.business_status = this.originBusinessStatus
                }
            }


            if(item === "4"){
                // 选择reject必须校验
                this.showReason = true;
                this.rules.reason[0].required = true;
            } else if(item==="3"){

                new Date().getFullYear()+"-"+new Date().getMonth()+1 +"-"+new Date().getDate()>9?new Date().getDate():"0"+new Date().getDate()
                var dt =new Date();
                var year=dt.getFullYear();
                var month=dt.getMonth()+1;
                var date=dt.getDate();
                var dateStr=year+"-"+month+"-"+(date>9?date:"0"+date);
                this.form.closingDate=dateStr;
            } else {
                this.showReason = false;
                this.rules.reason[0].required = false;
                /*this.form.closingDate="";
                this.form.reason="";*/
                /*this.form.closingDate = null*/
            }
        },
        selectOwnerChange(index){
            debugger
            this.form.ownerId =this.filterUserList[index].employeeId
            this.form.deptId=this.filterUserList[index].deptId
            this.form.owner =this.filterUserList[index].value
            this.selectOwnerItem=this.filterUserList[index]
        },
        handleSelect(item) {
        },
        showFileList(row) {
            let ls = [];
            let str = row.attachment
            let len = 0;
            if (str) {
                str.split(",").forEach(i => {
                    len = len + 1
                    ls.push(process.env.VUE_APP_BASE_API + i);
                });
            }
            return {'data': ls, 'len': len}
        },
        /** 查询goodCatch列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            if (!this.$auth.hasPermi("business:goodCatch:searchAll")) {
                this.queryParams.employeeId = this.user.employeeId
            }
            if (null != this.daterangeDate && '' != this.daterangeDate) {
                this.queryParams.params["beginDate"] = this.daterangeDate[0];
                this.queryParams.params["endDate"] = this.daterangeDate[1];
            }
            listGoodCatch(this.queryParams).then(response => {
                console.log(response)
                this.goodCatchList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        getDeptList() {
            getDeptList().then(res => {
                console.log(res)
                this.deptList = res.data
                console.log(this.deptList)
                const userDeptId = this.user.deptId
                const userDept = this.deptList.find(item => item.deptId === userDeptId)
                this.userDeptOwner = userDept.owner
                const ownerMessage =  {'value': userDept.owner, "userId": null, "deptId": userDeptId,"employeeId":this.user.employeeId}
                this.userNameList.push(ownerMessage)
            })
        },
        getUserNameList() {
            getUserNameList().then(res => {
                let data = res.data
                console.log(data)
                let result = []
                data.forEach(i => {
                    result.push({'value': i.userName, "userId": i.userId, "deptId": i.deptId,"employeeId":i.employeeId})
                })
                this.userNameList = result
                /*this.userNameList = res.data*/
            })
        },
        deptFormatter(row) {
            let res = this.deptList.find(i => {
                return row.deptId == i.deptId
            });
            return res && res.deptName;
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                date: null,
                deptId: null,
                employeeId: null,
                employeeName: null,
                ownerId:null,
                owner:null,
                solution:null,
                title: null,
                result: null,
                dueDate: null,
                closingDate: null,
                status: null,
                reconfirm:null,
                remark: null,
                attachment: null,
                comment:null,
                reason:null,
                isSendMail: false,
                ownerDept:null
            };
            this.resetForm("form");
            this.fileList = []
        },
        // 文件上传
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeDate = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            console.log(selection)
            this.ids = selection.map(item => item.id)
            this.reClosedMultiple = !selection.find(item => item.reconfirm === 'open');
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.showReconfirm = !this.$auth.hasPermi('business:goodCatch:reconfirm');
            this.editPermit = false;
            this.open = true;
            this.title = "Add GoodCatch";
            this.form.reconfirm = "open"
            this.form.employeeId = this.user.employeeId
            this.form.employeeName = this.user.name
            this.form.deptId = this.user.deptId
            this.form.date = new Date()
            this.form.owner = this.userDeptOwner
            this.isOwnerStatus = 1;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            // 判断有没有权限
            this.showReconfirm = !this.$auth.hasPermi('business:goodCatch:reconfirm');
            // 获取当前用户
            let user = this.user;
            // 如果当前行不是用户本人的数据，且没有权限，则不可编辑
            this.editPermit = user.employeeId !== row.employeeId && !this.$auth.hasPermi('business:goodCatch:reconfirm') &&
                user.name !== row.owner;
            const id = row.id || this.ids
            this.isOwnerStatus = 2
            getGoodCatch(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "Edit GoodCatch";
                //如果owner是自己，只能Ongoing
                if(this.form.owner === this.user.name){
                    this.isOwnerStatus = 0
                }
            });
            if(row.reconfirm ==='reject'){
                this.rules.comment[0].required = true;
                this.showComment = true;
            }
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    /*let f = true
                    this.userNameList.forEach(item => {
                        if (item.employeeId === this.form.ownerId) {
                            f = false
                        }
                    })
                    if (f) {
                        this.$message.error("Owner has wrong name")
                        return !f
                    }*/
                    let userNames = this.userNameList
                    // 查找用户
                    const owner = userNames.find(i => {
                        return i.value === this.form.owner
                    })
                    if (owner === undefined) {
                        this.$message.error("Owner has wrong name")
                        return false;
                    }
                    // 获取owner历史数据，如果没有则添加，如果有则追加
                    let ownHis = this.form.ownerHistory;
                    // 新建当前的owner
                    const ownerData = {
                        "owner": {
                            "userName": owner.value,
                            "userId": owner.userId,
                            "employeeId": owner.employeeId,
                            "deptId": owner.deptId
                        }, "date": new Date(), "editor": this.user.name
                    }

                    this.form.ownerId = ownerData.owner.employeeId
                    this.form.owner = ownerData.owner.userName
                    /*this.form.deptId = ownerData.owner.deptId*/

                    if (null === ownHis || undefined === ownHis || "" === ownHis) {
                        this.form.ownerHistory = JSON.stringify([ownerData])
                    } else {
                        let ownHisList = JSON.parse(ownHis)
                        // 获取最后一个
                        const lastData = ownHisList[ownHisList.length - 1]
                        // 判断是否相同
                        if (lastData.owner.userId !== ownerData.owner.userId) {
                            ownHisList.push(ownerData)
                            this.form.ownerHistory = JSON.stringify(ownHisList)
                        }
                    }
                    /*// 获取owner历史数据，如果没有则添加，如果有则追加
                    let ownHis = this.form.ownerHistory;
                    var ownerDeptId=0;
                    /!*console.log(this.userNameList);*!/
                    for (var i=0;i<this.userNameList.length;i++){
                        /!*console.log(this.userNameList[i].employeeId+"=="+ this.form.ownerId+(this.userNameList[i].employeeId == this.form.ownerId))*!/
                        if(this.userNameList[i].employeeId == this.form.ownerId){
                            ownerDeptId = this.userNameList[i].deptId;
                        }
                    }
                    // 新建当前的owner
                    const ownerData = {
                        "owner": {
                            "userName": this.form.owner,
                            "userId": this.form.ownerId,
                            "deptId": ownerDeptId
                        }, "date": new Date(), "editor": this.user.name
                    }

                    if (null === ownHis || undefined === ownHis || "" === ownHis) {
                        this.form.ownerHistory = JSON.stringify([ownerData])
                    } else {
                        let ownHisList = JSON.parse(ownHis)
                        // 获取最后一个
                        const lastData = ownHisList[ownHisList.length - 1]
                        // 判断是否相同
                        if (lastData.owner.userId !== ownerData.owner.userId) {
                            ownHisList.push(ownerData)
                            this.form.ownerHistory = JSON.stringify(ownHisList)
                        }
                    }*/
                    // 判断remark是否更新
                    if (this.form.remark !== this.form.remarkNew) {
                        if (this.form.remark === null || this.form.remark === undefined || this.form.remark === "") {
                            this.form.remark = JSON.stringify([this.form.remarkNew])
                        } else {
                            let remarkJson = []
                            try {
                                remarkJson = JSON.parse(this.form.remark)
                            } catch (e) {
                                remarkJson = [this.form.remark]
                            }
                            if (this.form.remarkNew === null || this.form.remarkNew === undefined) {
                                this.form.remark = JSON.stringify(remarkJson)
                            } else {
                                remarkJson.push(this.form.remarkNew)
                                this.form.remark = JSON.stringify(remarkJson)
                            }
                        }
                    }

                    let self = this;

                    /*self.form.isSendMail = true
                        if (self.form.id != null) {
                            updateGoodCatch(self.form).then(response => {
                                self.$modal.msgSuccess("Edit Success");
                                self.open = false;
                                self.getList();
                            });
                        } else {
                            addGoodCatch(self.form).then(response => {
                                self.$modal.msgSuccess("Add Success");
                                self.open = false;
                                self.getList();
                            });
                        }*/
                    /* self.form.isSendMail = true
                     if (this.form.id != null) {
                                             updateGoodCatch(this.form).then(response => {
                                                 this.$modal.msgSuccess("Edit Success");
                                                 this.open = false;
                                                 this.getList();
                                             });
                                         } else {
                                             addGoodCatch(this.form).then(response => {
                                                 this.$modal.msgSuccess("Add Success");
                                                 this.open = false;
                                                 this.getList();
                                             });
                                         }*/
                    self.form.isSendMail = true
                    if (self.form.id != null) {
                        updateGoodCatch(self.form).then(response => {
                            self.$modal.msgSuccess("Edit Success");
                            self.open = false;
                            self.getList();
                        });
                    } else {
                        addGoodCatch(self.form).then(response => {
                            self.$modal.msgSuccess("Add Success");
                            self.open = false;
                            self.getList();
                        });
                    }

                    /*this.$confirm('是否发送邮件', 'confirm', {
                        confirmButtonText: "好的",
                        cancelButtonText: "no",
                        type: 'warning'
                    }).then(function (result) {
                        self.form.isSendMail = true
                    }).catch(() => {
                        self.form.isSendMail = false
                    }).then(function () {

                    });*/
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('Delete GoodCatch "' + ids + '"？').then(function () {
                return delGoodCatch(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("Delete Success");
            }).catch(() => {
            });
        },
        /** reClosed按钮操作 */
        handleReClosed() {
            const ids = this.ids;
            this.$modal.confirm('ReClosed GoodCatch ' + ids.length + ' Data？').then(function () {
                return reClosedGoodCatch(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("ReClosed Success");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('business/goodCatch/export', {
                ...this.queryParams
            }, `goodCatch_${new Date().getTime()}.xlsx`)
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "Good Catch Import";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('business/goodCatch/importTemplate', {}, `good_catch_template_${new Date().getTime()}.xlsx`)
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "Result", {dangerouslyUseHTMLString: true});
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        }
    }

};

</script>
<style scoped>
.el-divider--horizontal{
    margin:5px !important;
}
</style>
